package com.lwl.office.dcconverter.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.URLUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.UUID;

public class ImgUtil {
    private static String temFolder;
    private static String downloadApi;

    static {
        try {
            Properties properties = new Properties();
            InputStream stream = ResourceUtil.getStream("dcconfig.properties");
            properties.load(stream);
            temFolder = properties.getProperty("img.store.folder");
            String api = properties.getProperty("img.store.download.api");
            String param = properties.getProperty("img.store.download.param");
            downloadApi = api+"?"+param+"=";
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void setTemFolder(String temFolder) {
        ImgUtil.temFolder = temFolder;
    }

    /**
     * 缓存图片数据，返回下载地址
     * @param data
     * @param filename
     * @return
     * @throws IOException
     */
    public static String storeTempImg(byte[] data,String filename) throws IOException {
        filename = UUID.randomUUID().toString().replace("-","")+filename;
        File file = new File(temFolder + filename);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        file.createNewFile();
        FileUtil.writeBytes(data,file);
        return downloadApi+URLUtil.encode(file.getPath());
    }

}
